<script setup lang="ts">
import SingleViewer from "@renderer/view/components/singleViewer/SingleViewer.vue";
import { computed, inject, onBeforeUnmount, onMounted, ref, watch } from "vue";
import {
  EnumViewType,
  loadSingleViewType,
} from "@renderer/assets/types";
import { useSystemSettingStore } from "@renderer/store/pinia/systemSetting";
import { postRequest } from "@renderer/api/request";
import API from "@renderer/api/api";

import { useImageDataStore } from "@renderer/store/pinia/imageData";
import {useViewManagerStore} from '@renderer/store/pinia/viewManager'
import { useHandlerTouchOrMouseOp } from "@renderer/view/components/singleViewer/useHandlerTouchOrMouseOp";
import _ from "lodash";
import { getActiveTabViewOp } from "@renderer/view/hooks/common";
const systemStore = useSystemSettingStore();

const {
  activeViewRef: activeView
} = getActiveTabViewOp()

const viewStore = useViewManagerStore();

const setActiveViewId = (view: any) => {
  viewStore.setTabActiveViewId(activeView.value.tabId,view)
}

watch(
  () => systemStore.quickLayout.value,
  (newValue, _) => {
    const [rows, cols]: string[] = newValue.split("*");
    const total = Number.parseInt(rows) * Number.parseInt(cols);
    viewStore.batchCreateQuickView(
      {
        patientUID:activeView.value.patientUID,
        seriesId: activeView.value.seriesId,
        viewMode: activeView.value.viewMode,
        tabId: activeView.value.tabId,
        viewType: '',
        total,
        groupId: activeView.value.tabId,
      }
    );
  },
);

const imgStore = useImageDataStore();

const viewArr = computed(() => {
  return viewStore.tabSubView[activeView.value.tabId];
});

const getContainerClass = computed(() => {
  const value = systemStore.quickLayout.value;
  const [rows, cols] = value.split("*");
  return `display: grid;
          grid-template-rows: repeat(${rows}, minmax(0, 1fr));
           grid-template-columns: repeat(${cols}, minmax(0, 1fr));
          `
});

const statusRef = ref({
  firstLoadFinish: true, // 是否加载了第一次的视图？
  isFirstShowFullScreen: false, // 是否已经显示过全屏？ 显示过则已经加载了全屏的组件
  isFullScreen: false, // 当前是否是全屏状态
});

const handleToggleFullScreen = (view) => {
  viewStore.setTabActiveViewId(activeView.value.tabId,view)
  statusRef.value.isFullScreen = !statusRef.value.isFullScreen;
  if (statusRef.value.isFullScreen) {
    statusRef.value.isFirstShowFullScreen = true;
  }
};
const setAspect = async ( args) => {
  const { viewId,width, height, viewType } = args;
  handleAspectChange({ viewId,width, height, viewType });
}

const handleAspectChange = ({ viewId,width, height, viewType }) => {
    setAspect2Server({ viewId,width, height, viewType });
    return;
};

const setAspect2Server = async ({ viewId,width, height, viewType }) => {
  const msg: loadSingleViewType = {
    opType: "setSize",
    size: {
      width,
      height
    },
    viewId: viewId,
    viewType
  };
  await postRequest(API.setSize, msg);
};

const activeViewHasImg = computed(() => {
  const viewId = activeView.value.viewId;
  return viewId in imgStore.imgSrcObj;
})

const managerRectArea = ref()
const managerRef = ref()
let resizeObserver: ResizeObserver
const watchResize = () => {
  resizeObserver = new ResizeObserver(
    _.debounce((entries) => {
      managerRectArea.value = managerRef.value.getBoundingClientRect()
    })
  )
  // 绑定监听的dom
  resizeObserver.observe(managerRef.value)
}

onMounted(() => {
  watchResize()
})
onBeforeUnmount(() => {
  resizeObserver.disconnect()
})

const {
  handleMousedown,
  handleMousemove,
  handleMouseup,
  handleTouchStart,
  handleTouchEnd,
  handleTouchmove,
  handleWheel,
} = useHandlerTouchOrMouseOp(managerRectArea, activeViewHasImg)

</script>

<template>
  <div class="w-full h-full"
       @mousedown="handleMousedown"
       @mousemove="handleMousemove"
       @mouseup="handleMouseup"
       @touchstart="handleTouchStart"
       @touchmove="handleTouchmove"
       @touchend="handleTouchEnd"
       @mouseleave="handleMouseup"
       @wheel="handleWheel"
       ref="managerRef"
       :style="getContainerClass">
    <div
      v-if="!statusRef.isFullScreen"
      v-for="item in viewArr"
      :class="[
        activeView.viewId === item.viewId ? 'active' : 'inactive',
        item.position,
        item.viewType,
      ]"
      class="img-operate-container box-border"
      @click="setActiveViewId(item)"
    >
      <single-viewer
        :view-id="item.viewId"
        :key="item.viewId"
        @dblclick="handleToggleFullScreen(item)"
        :view-type="item.viewType"
        :img-src="imgStore.imgSrcObj[item.viewId]"
        :fourCornerInfo="imgStore.fourCornelObj[item.viewId]"
        @set-aspect="(args) => setAspect( args)"
      />
    </div>

    <div v-else class="row-span-full col-span-full active">
      <single-viewer
        :view-id="activeView.viewId"
        @dblclick="handleToggleFullScreen(activeView)"
        :img-src="imgStore.imgSrcObj[activeView.viewId]"
        :view-type="EnumViewType.stack"
        @set-aspect="(args) => setAspect(args)"
        :fourCornerInfo="imgStore.fourCornelObj[activeView.viewId]"
      />
    </div>
  </div>
</template>

<style scoped>
.active {
  @apply border-4  border-(--color-active);
}
.inactive {
  @apply border-4 border-[#d1d5db];
}
</style>
